Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
React/TS prevent form submission on enter while using "required" tag

There are already a bunch of helpful answers on preventing form submit on enter (example1, example2) However none of these work if I want to include the "required" tag on any of the inputs. See code below:

    
    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        // do other stuff
    };
    
    return (
            <form id="LocationForm" onSubmit={handleSubmit} >
                <input type="text" placeholder="Please add country" onKeyUp={handleCountryChange} />
                <input type="text" placeholder="Please add city" onKeyUp={handleCityChange} required />
                <input type="submit" value="Submit" />
            </form>
    )

When I press enter in the first input, a dialog pops up that says "This field is required". Ideally, I only want this to pop up when I click the submit button and not when I press enter in any other input. Of course I could implement this logic myself without using the required tags, but would rather avoid re-inventing the wheel here... unless there is some other standard practice that people use. Any pointers?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try adding onKeyPress={(e) => e.preventDefault() to the <form>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!